/*
 * @Descripttion: 检查任务页面
 * @version: 
 * @Author: linPing
 * @Date: 2019-10-29 12:25:00
 * @LastEditTime: 2019-11-04 17:01:41
 */



import React, { Fragment } from 'react';

import { observer, inject } from 'mobx-react';
import Toast, { DURATION } from 'react-native-easy-toast';
import NavigationBar from '../../common/NavigationBar';
import GlobalStyles from "../../res/styles/GlobalStyles";
import { ButtonGroup } from 'react-native-elements'
import NavigationUtil from '../../navigator/NavigationUtil'
import OffLineImagePick from "../../common/OffLineImagePick";
import Icon from "../../common/Images";
import AsyncStorageUtils from "../../expand/AsyncStorage";
import ViewUtil from "../../util/ViewUtil";
import SafeAreaViewPlus from "../../common/SafeAreaViewPlus";
import VisibleView from "../../common/VisibleView";

import ActionSheet from 'react-native-actionsheet';

import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    Button,
    View,
    Text,
    StatusBar,
    FlatList,
    Image,
    TextInput,
    NativeModules,
    Alert,
    Dimensions,
    DeviceEventEmitter,

} from 'react-native';
import { thisTypeAnnotation } from '@babel/types';

const { width, height } = Dimensions.get('window')
// import { TouchableOpacity } from 'react-native-gesture-handler';
var ImagePicker = NativeModules.ImageCropPicker;
@inject('appStore')
@observer
export default class TaskRoomList extends React.Component {
    constructor(props) {
        super(props)

        this.params = this.props.navigation.state.params
        this.type = this.params.type
        this.title = this.params.type===1?"添加隐患":"添加亮点"
        this.state = {
            inputText: "",
            defaultValue: "",
            imgShowList: [],
            showAction: false,
            checkItem: null,
            saveState:true,
            stroeData:{}
        }
        this.key = this.params.key
        this.type = this.params.type

    }

    componentDidMount(){
        // if(this.params.id && this.params.id!==""){
        //     AsyncStorageUtils.loadById(this.params.key).then(stroeData=>{
        //         this.setState({
        //             stroeData
        //         })
        //     })
        // }
        this.initData()
    }
    initData(){
        const {item}=this.params
        if(this.params&&item){
            this.setState({
                stroeData:item,
                defaultValue:item.desc,
                checkItem:item.checkItem,
                inputText:item.desc,
                imgShowList:item.images
            })
        }
    }

    genID(length){
        return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
      }
   getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    onBack = () => {
        if(this.state.saveState) {
            NavigationUtil.goBack(this.props.navigation)
            return false
        }
        Alert.alert('确认', '隐患还未保存，是否放弃编辑？',
        [{ text: '取消', onPress: () => { console.log('取消') } },
        {
            text: '确定',
            onPress: () => {
                NavigationUtil.goBack(this.props.navigation);
            }
        }])

       
    }
        /**
       * 本地存储检查记录
       * 存储的时候采用key-id方式
       * key：是任务ID+房间ID
       * id：本地检查记录生成ID
       * 进入房间通过 AsyncStorageUtils.getAllDataForKey(key)获取下面的所有隐患
       * 提交成功后 AsyncStorageUtils.clearMapForKey(key) 删除隐患
       * 
       * 结构
       * 
       * {
       *    key:生成一个临时ID
       *    checkDate:""
       *    images[],
       *    type:{0:亮点,1:隐患},
       *    desc:'描述'
       *    checkItem:{id:'',name:'',desc:''}
       *    
       * }
       */
    onSave() {
        const {key,type} = this.params
        const {inputText,imgShowList,checkItem,stroeData} = this.state
        if(!key){
            this.toast.show('任务不存在', 800)
            return false
        }

        if(inputText===""){
            this.toast.show('请填写描述', 800)
            return false
        }
        if(!checkItem && this.type===1){
            this.toast.show('请选择隐患项', 800)
            return false
        }

        
        const id = stroeData.key?stroeData.key:this.genID(16)
 
        let newData = {
            key: id,
            type:type,
            images:imgShowList,
            desc:inputText,
            checkItem:checkItem,
            checkDate:this.getNowFormatDate()
            
        }
        this.setState({
            stroeData:newData
        })
        AsyncStorageUtils.saveById(key,id,newData)
       
     
        DeviceEventEmitter.emit('refresh',{
            'newMessage':'刷新',
          })
        this.setState({
            saveState:true
        },()=>{
            this.onBack()
        })
        
    
        
    }
    unSave(){//内容修改时把保存状态设为false
        this.setState({
            saveState:false
        })
    }
    getImgList(data) {

    }


    showAction() {
        this.setState({
            showAction: true
        })
    }
    //添加图片按钮
    _AddStarPhoto() {
        return (
            <TouchableOpacity
                onPress={() => {
                    let _this = this

                    this.ActionSheet.show()
                }
                }
            >
                <View style={styles.addStarIocn}>
                    <Image
                        source={Icon.common.iconAddBold}
                    />
                </View>
            </TouchableOpacity>
        )
    }
    _ImgDelet(img) {
        let temp = this.state.imgShowList
        let index = temp.findIndex(item => item === img)

        temp.splice(index, 1)
        this.unSave()
        this.setState({
            imgShowList: temp
        })
    };
    //显示大图
    _ImgShowBig(index) {
        let media = this.state.imgShowList.map(item => ({ photo: item }));
        NavigationUtil.goPage({ media: media, index: index }, "PhotoPage")
    }
    showLocalImage(item, index) {

        return (
            <View style={styles.imgBox}>
                <VisibleView
                    visible={true}>
                    <TouchableOpacity
                        onPress={() => this._ImgDelet(item)}
                        underlayColor="#fff"
                        style={styles.imgCloseTouch}
                    >
                        <Image
                            style={styles.imgClose}
                            source={Icon.common.iconImgDeletWhite}
                        />
                    </TouchableOpacity>
                </VisibleView>
                <TouchableOpacity
                    onPress={() => this._ImgShowBig(index)}
                    underlayColor="#fff"
                    style={styles.conterPhotoTouch}
                >
                    <Image
                        source={{ uri: item }}
                        style={styles.conterPhoto}
                    />
                </TouchableOpacity>
            </View>
        )
    }


    actionsheetItemClick = (id) => {
        alert(id);
    }
    componentWillUnmount() {

    }

    pickSingleWithCamera = () => {
        ImagePicker.openCamera({
            cropping: false,
            compressImageMaxWidth: 1200,
            compressImageMaxHeight: 960,
            compressImageQuality: 0.9,
        }).then(image => {
            let images = [image].map(item => item.path)
            console.log(images)

            this.setState({
                imgShowList: this.state.imgShowList.concat(images)
            });
            this.unSave()
        }).catch(e => console.log(e));
    }
    picksingle() {
        ImagePicker.openPicker({
            cropping: false,
            multiple: true,
            mediaType: 'photo',
            compressImageMaxWidth: 1280,
            compressImageMaxHeight: 960,
            compressImageQuality: 0.5,
        }).then(image => {

            let images = image.map(item => item.path)

            this.setState({
                imgShowList: this.state.imgShowList.concat(images)
            });
            this.unSave()

        }).catch(e => {
            console.log(e)
            Alert.alert(e.message ? e.message : e);
        })
    }


    showData(){
        const {key} = this.params
       
        AsyncStorageUtils.getAllDataForKey(key).then(data=>{
          
            NavigationUtil.goPage({data},"ShowDataPage")
        })
    }
    clearData(){
        const {key} = this.params
        AsyncStorageUtils.clearMapForKey(key)
        // AsyncStorageUtils.deleteId(key,id)
    }
    render() {
        const { navigation } = this.props
        const { appStore, appStore: { theme } } = this.props


        let statusBar = {
            backgroundColor: theme,
            barStyle: 'light-content',
        };
        let navigationBar =
            <NavigationBar
                title={this.title}
                statusBar={statusBar}
                leftButton={ViewUtil.getLeftBackButton(() => this.onBack())}
                rightButton={ViewUtil.getRightButton("保存", () => this.onSave())}
                style={{ backgroundColor: theme }}
            />;

        const item = this.originalData



        return (

            <SafeAreaViewPlus style={GlobalStyles.root_container}>

                {navigationBar}


                {/* <Button
                    title={"清除数据"}
                    onPress={()=>this.clearData()}
                ></Button>
                <Button
                    title={"显示数据"}
                    onPress={()=>this.showData()}
                ></Button> */}

                <ScrollView style={{flex:1}}>
                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'选择图片'}
                    options={['拍照', '图片库', '取消']}
                    cancelButtonIndex={2}
                    //   destructiveButtonIndex={1}
                    onPress={(index) => {
                        if (index === 0) {
                            this.pickSingleWithCamera()
                        } else if (index === 1) {
                            this.picksingle()
                        }
                    }}
                />
                <View style={styles.container}>
                    <View style={styles.starPhoto}>
                        <FlatList
                            data={this.state.imgShowList}
                            // style={styles.conterPhotoList}
                            // horizontal={true}
                            extraData={this.state}
                            numColumns={3}
                            contentContainerStyle={styles.listViewStyle}
                            keyExtractor={(item, index) => item + index.toString()}
                            ListFooterComponent={this._AddStarPhoto()}
                            renderItem={({ item, index }) => this.showLocalImage(item, index)}
                        />
                    </View>
                    <TextInput
                        style={styles.textInputStyle}
                        placeholder={this.type?"请输入隐患问题描述":"请输入亮点描述"}
                        placeholderTextColor="#999"  //占位符颜色
                        editable={true}//是否可编辑
                        maxLength={500}//限制文本框的最多字符数
                        multiline={true}//文本框中可以输入多行文字
                        numberOfLines={6}
                        underlineColorAndroid={'transparent'}//输入框的线框为透明
                        textAlignVertical='top'// 设置文本垂直方向布局方式
                        keyboardType='default'//软键盘的类型
                        autoFocus={false}//自动获取焦点
                        onChangeText={(text) => {
                            // if(text.length >= 200){
                            //     let sliceText = text.slice(0,200);
                            //     this.setState({
                            //         inputText:sliceText
                            //     },()=>{
                            //         this.refs.toast.show('亮点描述，不超过200个字', 800)
                            //     })
                            // }else{
                            //     this.setState({inputText:text})
                            // }
                            this.unSave()
                            this.setState({ inputText: text })
                        }
                        }//文本内容发生变化时，执行回调函数，改变后的文本内容会作为参数传递
                        defaultValue={this.state.defaultValue}
                    />
                    
                    <VisibleView visible={this.type===1}>

              

                    {ViewUtil.getCustomItem(() => {
                        NavigationUtil.goPage({
                            getCheckItem: (checkItem) => {
                                this.setState({ checkItem })
                            }
                        }, "TreeSelect")

                    }, "选择检查项")}

                    <View style={{ backgroundColor: "#fff", padding: 20 ,marginTop:1}}>
                        
                        <VisibleView visible={!this.state.checkItem}>
                            <Text style={{ fontSize: 13, color: "#999", textAlign: "center" }}>暂无检查项</Text>
                        </VisibleView>
                        <VisibleView visible={this.state.checkItem}>
                            <Text style={{ fontSize: 14, color: "#333", marginBottom: 12,lineHeight:22  }}>{this.state.checkItem && this.state.checkItem.name}</Text>
                            <Text style={{ fontSize: 13, color: "#666",lineHeight:22 }}>{this.state.checkItem && this.state.checkItem.desc}</Text>
                        </VisibleView>

                    </View>

                    </VisibleView>
                </View>

                </ScrollView>
                <Toast
                        ref={o=>this.toast=o}
                        position={'top'}
                        positionValue={130}
                        fadeInDuration={800}
                        fadeOutDuration={400}
                        opacity={0.7}
                    />
            </SafeAreaViewPlus>

        )
    }

};


const styles = StyleSheet.create({
    container: {
        // flex: 1,
    },
    listViewStyle: {

        // 主轴方向
        flexDirection: 'row',
        // 一行显示不下,换一行
        // flexWrap: 'wrap',


        // 侧轴方向
        // alignItems: 'center', // 必须设置,否则换行不起作用
    },
    imgBox: {
        marginBottom: 10
    },
    textInputStyle: {
        marginBottom: 20,
        height: 240,
        paddingLeft: 24,
        paddingRight: 24,
        paddingTop: 20,
        paddingBottom: 20,
        backgroundColor: '#fff',
        borderColor: "rgba(216,216,216,0.50)",
        borderWidth: 0.5,
    },
    starPhoto: {
        backgroundColor: '#fff',
        padding: 15
    },
    conterPhotoList: {

    },
    conterPhoto: {
        borderRadius: 4,
        width: width / 3.7,
        height: width / 3.7,
        marginRight: 16,
    },
    headerSave: {
        paddingLeft: 24,
        paddingRight: 24
    },
    conterPhotoTouch: {
        position: 'relative',
        zIndex: 1
    },
    imgCloseTouch: {
        position: 'absolute',
        zIndex: 1999,
        right: 20,
        top: 5,
    },
    addStarIocn: {
        borderRadius: 4,
        width: width / 3.7,
        height: width / 3.7,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(216,216,216,0.30)',
    },

    preview: {
        flex: 1,
        justifyContent: 'space-between',
        alignItems: 'flex-end',
        flexDirection: 'row',
    },
    toolBar: {
        width: 200,
        margin: 40,
        backgroundColor: '#000000',
        justifyContent: 'space-between',

    },
    button: {
        flex: 0,
        backgroundColor: '#fff',
        borderRadius: 5,
        color: '#000',
        padding: 10,
        margin: 40,
    },
    // But: {
    //     flexDirection:'row',
    //     width:width,
    //     ...paddingTB(16),
    //     marginTop:px2dp(16),
    //     justifyContent:'center',
    //     alignItems:'center',
    // },
    // ButStyle: {
    //     fontSize:px2sp(34),
    //     width:px2dp(600),
    //     fontWeight:'100',
    //     ...marginLR(40),
    //     lineHeight:px2dp(72),
    //     backgroundColor:'#379ef6',
    //     height:px2dp(72),
    //     borderRadius:px2dp(36),
    //     color:'#fff'
    // },

});

